﻿using System.Collections.Generic;
using System.Data;

namespace Marmat.Data
{
    public class DataTableHelper
    {
        public string TableName { get; set; }
        public string PrimaryKey { get; set; }

        public string GetSaveString(DataTable dt)
        {
            var Suffix = new Suffix();
            return this.GetSaveString(dt, Suffix);
        }

        public string GetSaveString(DataTable dt, Suffix Suffix)
        {
            var Columns = new List<string>();
            foreach (DataColumn dc in dt.Columns)
            {
                if ((dc.ColumnName ?? "") != (this.PrimaryKey ?? ""))
                {
                    Columns.Add(dc.ColumnName);
                }
            }

            return this.GetSaveString(dt, Columns.ToArray(), Suffix);
        }

        public string GetSaveString(DataTable dt, string[] Columns)
        {
            var Suffix = new Suffix();
            return this.GetSaveString(dt, Columns, Suffix);
        }

        public string GetSaveString(DataTable dt, string[] Columns, Suffix Suffix)
        {
            var Result = new System.Text.StringBuilder();
            var Helper = new DataRowHelper();
            Helper.TableName = this.TableName;
            Helper.Suffix = new Suffix();
            Helper.PrimaryKey = this.PrimaryKey;
            foreach (DataRow dr in dt.Rows)
            {
                string Sql = Helper.GetSaveString(dt, dr, Columns);
                if (!string.IsNullOrEmpty(Sql))
                {
                    Result.Append(Result.Length > 0 ? "\r\n" : "" + Sql);
                }
            }

            return Result.ToString();
        }
    }
}